package cn.tedu.fengyuback.personal.service.impl;

import cn.tedu.fengyuback.personal.mapper.PersonalMapper;
import cn.tedu.fengyuback.personal.mapper.RepliedMapper;
import cn.tedu.fengyuback.personal.pojo.dto.ArticlesQuery;
import cn.tedu.fengyuback.personal.pojo.dto.FavoritesQuery;
import cn.tedu.fengyuback.personal.pojo.dto.LikesQuery;
import cn.tedu.fengyuback.personal.pojo.vo.ArticlesVO;
import cn.tedu.fengyuback.personal.pojo.vo.FavoritesVO;
import cn.tedu.fengyuback.personal.pojo.vo.LikesVO;
import cn.tedu.fengyuback.personal.service.RepliedService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class RepliedServiceImpl implements RepliedService {
    @Autowired
    private RepliedMapper repliedMapper;
    @Autowired
    private PersonalMapper personalMapper;
    @Override
    public List<ArticlesVO> selectReplied(Long userId, Long questionId) {
        log.debug("开始处理【查询用户发布的回答】的业务，参数：userId={},questionId={}",userId,questionId);
        ArticlesQuery articlesQuery = new ArticlesQuery();
        articlesQuery.setUserId(userId);
        articlesQuery.setQuestionId(questionId);
        articlesQuery.setStatus("1");
        List<ArticlesVO> list = repliedMapper.selectReplied(articlesQuery);
        for (ArticlesVO articlesVO : list){
            //查询是否点赞
            likesQuery(articlesVO, userId);
            //查询是否收藏
            favoritesQuery(articlesVO, userId);
        }
        return list;
    }

    /**
     * 查询用户是否收藏该文章
     * @param articlesVO
     * @param userId
     */
    private void favoritesQuery(ArticlesVO articlesVO, Long userId) {
        FavoritesQuery favoritesQuery = new FavoritesQuery();
        favoritesQuery.setArticleId(articlesVO.getId());
        favoritesQuery.setUserId(userId);
        FavoritesVO favoritesVO = personalMapper.selectFavorites(favoritesQuery);
        if (favoritesVO != null){
            articlesVO.setFavoritesId(favoritesVO.getId());
            articlesVO.setFavoritesStatus("primary");
        }else {
            articlesVO.setFavoritesStatus("");
        }
    }

    /**
     * 查询用户是否点赞该文章
     * @param articlesVO
     */
    private void likesQuery(ArticlesVO articlesVO, Long userId) {
        LikesQuery likesQuery = new LikesQuery();
        likesQuery.setArticleId(articlesVO.getId());
        likesQuery.setUserId(userId);
        LikesVO likesVO = personalMapper.selectLikes(likesQuery);
        if (likesVO != null){
            articlesVO.setLikesId(likesVO.getId());
            articlesVO.setLikesStatus("primary");
        }else {
            articlesVO.setLikesStatus("");
        }
    }
}
